package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 *@Description:在域中存数据,并取值
 *@author:刘哥
 *@Date:86180 2022/8/30 16:37
 */
@Controller
@RequestMapping("test")
//@SessionAttributes注解的作用,当我们使用model或者modelandview保存数据的时候如果是这两个key(键)就保存到session中,
//@SessionAttributes({"sessionattr","sessionattr2"})
public class TestController {
    @RequestMapping("test01")
    public String test1(HttpServletRequest request, HttpSession session) {
        request.setAttribute("requestAttr", "申志恒");
        request.getSession().setAttribute("sessionattr", "18");
        session.setAttribute("sessionattr2", "是傻逼");
        return "redirect:/index.jsp";

    }
    @RequestMapping("test02")
    public String test2(HttpServletRequest request, HttpSession session) {
        request.setAttribute("requestAttr", "申志恒");
        request.getSession().setAttribute("sessionattr", "18");
        session.setAttribute("sessionattr2", "是傻逼");
        return "/index.jsp";
    }

    /**
     * model属性回写结果
     *  通过model可以将数据保存到request中
     *
     */
    @RequestMapping("/model")
    public String test03(Model model){
        model.addAttribute("requestAttr", "申志恒");
        model.addAttribute("sessionattr", "18");
        model.addAttribute("sessionattr2", "是傻逼");
        return "/index.jsp";
    }

    /**
     *  在重定向的时候, model中的数据会被当做请求参数拼接到地址中,这就是和request的区别
     * @param model
     * @return
     */
    @RequestMapping("/model1")
    public String test04(Model model){
        model.addAttribute("requestAttr", "申志恒");
        model.addAttribute("sessionattr", "18");
        model.addAttribute("sessionattr2", "是傻逼");
        return "redirect:/index.jsp";
    }

    /**
     * @param modelAndView:可以回写数据和传递页面,传参方式和model一样，同样不可以重定向,重定向时参数拼接在路径后
     * @return
     */
    @RequestMapping("modelView")
    public ModelAndView test05(ModelAndView modelAndView){
        modelAndView.addObject("requestAttr", "申志恒");
        modelAndView.addObject("sessionattr", "18");
        modelAndView.addObject("sessionattr2", "是傻逼");

        modelAndView.setViewName("/index.jsp");//存放跳转的页面、
        return modelAndView;
    }
    @RequestMapping("/clear")
    public String clear(SessionStatus status){
    // 移除通过SessionAttributes存入的session
        status.setComplete();//
        return "redirect:/index.jsp";
    }

}
